import {AnyAction, Reducer} from 'redux';
import {EffectsCommandMap} from 'dva';
import {fetch, batchDelete, addOrUpdate, saveMenus} from './service';
import {IRole} from '../data';
import {Pagination} from '@/models/data';
import {message} from 'antd';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelState {
  data: {
    list: IRole[];
    pagination: Partial<Pagination>;
  };
}

export interface ModelType {
  namespace: string;
  state: ModelState;
  effects: {
    fetch: Effect;
    saveMenus: Effect;
    batchDelete: Effect;
    addOrUpdate: Effect;
  };
  reducers: {
    save: Reducer<{}>;
  };
}

const Model: ModelType = {
  namespace: 'roleList',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    * fetch({payload}, {call, put}) {
      const response = yield call(fetch, payload);
      yield put({
        type: 'save',
        payload: response,
      });
    },
    * saveMenus({payload, callback}, {call, put}) {
      const response = yield call(saveMenus, payload);
      if (response.status === 'ok') {
        message.success(response.message);
      }
      if (callback) callback();
    },

    * batchDelete({payload}, {call, put}) {
      const response = yield call(batchDelete, payload);
      if (response.status === 'ok') {
        message.success('删除成功');
      }
      //@ts-ignore
      window.g_app._store.dispatch({
        type: 'roleList/fetch',
      });
    },
    * addOrUpdate({payload, callback}, {call, put}) {
      const response = yield call(addOrUpdate, payload);
      if (response.status === 'ok') {
        message.success(response.message);
      }
      //@ts-ignore
      window.g_app._store.dispatch({
        type: 'roleList/fetch',
      });
      if (callback) callback();
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
  },
};

export default Model;
